<template>
  <transition>
    <div v-show="visible" class="my-message" :style="positionStyle">
      hello
      {{ message }}
      {{ type }}
    </div>
  </transition>
</template>
<script>
export default {
  data() {
    return {
      message: "",
      type: "",
      visible: false,
      duration: 3000, //3秒
      onClose: null,
      showClose: false,
      closed: false,
      verticalOffset: 20,
      timer: null,
      dangerouslyUseHTMLString: false,
      center: false,
    };
  },
  computed: {
    positionStyle() {
      return {
        top: `${this.verticalOffset}px`,
      };
    },
  },
  mounted() {
    this.startTimer();//定时器触发删除数组里的实例
    //3秒之后销毁
    if (this.duration > 0) {
      this.timer = setTimeout(() => {
        this.$destroy(); //销毁当前实例
        this.$el.parentNode.removeChild(this.$el); //销毁dom元素
      }, this.duration);
    }
  },
  methods: {
    close() {
      this.closed = true;
      if (typeof this.onClose === "function") {
        this.onClose(this);
      }
    },
    clearTimer() {
      clearTimeout(this.timer);
    },

    startTimer() {
      if (this.duration > 0) {
        this.timer = setTimeout(() => {
          if (!this.closed) {
            this.close();
          }
        }, this.duration);
      }
    },
  },
};
</script>
<style>
.my-message {
  position: fixed;
  /* top:20px; */
  left: 50%;
  transform: translateX(-50%);
  min-width: 300px;
  border-radius: 5px;
  background: red;
  height: 40px;
  line-height: 40px;
  display: flex;
  color: #fff;
  transition: all 0.4s linear;
}
/*transition动画实现淡入淡出*/
.v-enter {
  opacity: 0;
}
.v-enter-active {
  transition: 1s linear;
}
.v-enter-to {
  opacity: 1;
}
</style>